package com.kaluli;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.kaluli.project.domain.entity.KllMainOrder;
import com.kaluli.project.utils.AlipayMd5Encrypt;
import com.kaluli.project.utils.HttpUtils;
import com.kaluli.project.utils.MD5Utils;
import com.kaluli.project.utils.RandomNumber;


public class test {

	public static void main(String[] args) throws Exception {
/*		test t = new test();
		t.init();
		t.createXml("c://test.xml");*/
		
		String str = " var sku = {\"detail\":{\"10;11\":{\"itemId\":\"38\",\"skuId\":\"228\",\"stock\":\"265\",\"price\":\"829.00\",\"discountPrice\":\"598.00\",\"status\":\"0\",\"storehouse_name\":\"\u9999\u6e2f\u76f4\u90ae\",\"storehouse_note\":\"\u9999\u6e2f\u76f4\u90ae\",\"discount\":\"7.2\"},\"10;13\":{\"itemId\":\"38\",\"skuId\":\"229\",\"stock\":\"60\",\"price\":\"829.00\",\"discountPrice\":\"598.00\",\"status\":\"0\",\"storehouse_name\":\"\u9999\u6e2f\u76f4\u90ae\",\"storehouse_note\":\"\u9999\u6e2f\u76f4\u90ae\",\"discount\":\"7.2\"}},\"attr\":[{\"data\":{\"10\":{\"name\":\"5\u78c5\",\"alias\":10}},\"name\":\"\u89c4\u683c\"},{\"data\":{\"11\":{\"name\":\"\u5de7\u514b\u529b\u5473\",\"alias\":11},\"13\":{\"name\":\"\u9999\u8349\u5473\",\"alias\":13}},\"name\":\"\u53e3\u5473\"}]}";
		String attr ="{\"\u5f88\u4e0d\u9519\":6,\"\u8d28\u91cf\u597d\":2,\"\u670d\u52a1\u597d\":4,\"\u7269\u6d41\u5feb\":4,\"\u6b63\u54c1\":3,\"\u5305\u88c5\u7cbe\u7f8e\":6,\"\u6548\u679c\u4e0d\u9519\":1}";
		System.out.println(attr);
		
//		String idNum = "34112419900329141x";
//		System.out.println(idNum.toUpperCase());
		
		String test="http://114.55.149.118:8181/nredi/base/api/service?method=order.create&serialno=14957185810263478&datetime=2017-05-2521:23:01&msgtype=xml&customer=SHRK&version=0.0.1&sign=%2FHNFBE2RLG1NVCTFPEEUJG%3D%3D&sign_method=md5&data=%3C%3Fxml+version%3D%221.0%22+encoding%3D%22UTF-8%22%3F%3E%0A%3Crequest%3E%3Chead%3E%3CmethodType%3Ecreate%3C%2FmethodType%3E%3ChgCode%3ENBC%3C%2FhgCode%3E%3CbusCode%3ESHRK%3C%2FbusCode%3E%3C%2Fhead%3E%3Cbody%3E%3Corder%3E%3CorderShop%3E20942%3C%2ForderShop%3E%3ChgArea%3E3105%3C%2FhgArea%3E%3CorderFrom%3EKALULI%3C%2ForderFrom%3E%3CpackageFlag%3E1%3C%2FpackageFlag%3E%3CbusOrderNo%3EKLL20170525055205206000307%3C%2FbusOrderNo%3E%3CpostFee%3E14.0%3C%2FpostFee%3E%3CinsuranceFee%3E0%3C%2FinsuranceFee%3E%3Camount%3E171.21%3C%2Famount%3E%3CbuyerAccount%3E26963041%3C%2FbuyerAccount%3E%3Cphone%3E15221038286%3C%2Fphone%3E%3CtaxAmount%3E18.21%3C%2FtaxAmount%3E%3CtariffAmount%3E0%3C%2FtariffAmount%3E%3CaddedValueTaxAmount%3E18.21%3C%2FaddedValueTaxAmount%3E%3CconsumptionDutyAmount%3E0%3C%2FconsumptionDutyAmount%3E%3CgrossWeight%3E2%3C%2FgrossWeight%3E%3CdisAmount%3E0.00%3C%2FdisAmount%3E%3CdealDate%3E2017-05-25+20%3A52%3A05%3C%2FdealDate%3E%3Cremark%3E%3C%2Fremark%3E%3Cpromotions%3E%3Cpromotion%3E%3CproAmount%3E0.0%3C%2FproAmount%3E%3C%2Fpromotion%3E%3C%2Fpromotions%3E%3Cgoods%3E%3Cdetail%3E%3CproductId%3E310517622300000986%3C%2FproductId%3E%3Cqty%3E1%3C%2Fqty%3E%3Cprice%3E139.0%3C%2Fprice%3E%3Camount%3E139.0%3C%2Famount%3E%3C%2Fdetail%3E%3C%2Fgoods%3E%3CisPayPush%3E0%3C%2FisPayPush%3E%3Cpay%3E%3Cpaytime%3E2017-05-25+20%3A52%3A14%3C%2Fpaytime%3E%3CpaymentNo%3E2017052521001003170228948231%3C%2FpaymentNo%3E%3CorderSeqNo%3E2017052521001003170228948231%3C%2ForderSeqNo%3E%3Csource%3EALIPAY%3C%2Fsource%3E%3Cidnum%3E41272719870311303X%3C%2Fidnum%3E%3Cname%3E%E6%9D%8E%E7%A3%8A%3C%2Fname%3E%3C%2Fpay%3E%3Clogistics%3E%3ClogisticsCode%3EYUNDA%3C%2FlogisticsCode%3E%3Cconsignee%3E%E6%9D%8E%E7%A3%8A%3C%2Fconsignee%3E%3Cprovince%3E%E4%B8%8A%E6%B5%B7%3C%2Fprovince%3E%3Ccity%3E%E4%B8%8A%E6%B5%B7%E5%B8%82%3C%2Fcity%3E%3Cdistrict%3E%E8%99%B9%E5%8F%A3%E5%8C%BA%3C%2Fdistrict%3E%3CconsigneeAddr%3E%E4%B8%8A%E6%B5%B7%E5%B8%82+%E4%B8%8A%E6%B5%B7%E5%B8%82+%E8%99%B9%E5%8F%A3%E5%8C%BA+%E4%B8%AD%E5%B1%B1%E5%8C%97%E4%B8%80%E8%B7%AF121%E5%8F%B7%E8%8A%B1%E5%9B%AD%E5%9D%8AA2%E5%8F%B73%E6%A5%BC%3C%2FconsigneeAddr%3E%3CconsigneeTel%3E15221038286%3C%2FconsigneeTel%3E%3CmailNo%3E000000%3C%2FmailNo%3E%3C%2Flogistics%3E%3C%2Forder%3E%3C%2Fbody%3E%3C%2Frequest%3E&appkey=1rqW1r97&secretKey=28lh22NGZ97s5w57";
		String utf8 = new String(test.getBytes(),"UTF-8");
//		System.out.println(getWeixinUrl());
		post();
		
	}
	
	
	public static void post() throws Exception{
		String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
"<request><head><methodType>create</methodType><hgCode>NBC</hgCode><busCode>SHRK</busCode></head><body><order><orderShop>20942</orderShop><hgArea>3105</hgArea><orderFrom>KALULI</orderFrom><packageFlag>1</packageFlag><busOrderNo>KLL20170726066234406000029</busOrderNo><postFee>17.0</postFee><insuranceFee>0</insuranceFee><amount>196.94</amount><buyerAccount>29396870</buyerAccount><phone>18890383089</phone><taxAmount>39.86</taxAmount><tariffAmount>0</tariffAmount><addedValueTaxAmount>39.86</addedValueTaxAmount><consumptionDutyAmount>0</consumptionDutyAmount><grossWeight>2</grossWeight><disAmount>177.92</disAmount><dealDate>2017-07-26 23:44:05</dealDate><remark></remark><promotions><promotion><proAmount>0</proAmount></promotion><promotion><proAmount>0</proAmount></promotion></promotions><goods><detail><productId>310517622300000855</productId><qty>1</qty><price>159.0</price><amount>159.0</amount></detail><detail><productId>310517622300000865</productId><qty>1</qty><price>159.0</price><amount>159.0</amount></detail></goods><isPayPush>0</isPayPush><pay><paytime>2017-07-26 23:44:48</paytime><paymentNo>2017072621001003220265877531</paymentNo><orderSeqNo>2017072621001003220265877531</orderSeqNo><source>ALIPAY</source><idnum>430111198610281710</idnum><name>周一夫</name></pay><logistics><logisticsCode>ZTO</logisticsCode><consignee>周一夫</consignee><province>贵州</province><city>贵阳市</city><district>南明区</district><consigneeAddr>贵州省 贵阳市 南明区 市东路50号贵阳中医学院</consigneeAddr><consigneeTel>18890383089</consigneeTel><mailNo>000000</mailNo></logistics></order></body></request>";
		StringBuffer bf = new StringBuffer();
		bf.append(data);
		bf.append("28lh22NGZ97s5w57");

		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
		bf.append(sf.format(new Date()));
		String reqData = MD5Utils.MD5_64bit(bf.toString());
		String sign = URLEncoder.encode(reqData.toUpperCase(), "UTF-8");
		StringBuffer url = new StringBuffer();
		url.append("http://114.55.149.118:8181/nredi/base/api/service?method=order.create");
		url.append("&serialno=" + new Date().getTime());
		url.append(RandomNumber.getRandom());
		url.append("&datetime=" + sf.format(new Date()));
		url.append("&msgtype=xml");
		url.append("&customer=" +"SHRK");
		url.append("&version=0.0.1");
		url.append("&sign=" + sign);
		url.append("&sign_method=md5");
		url.append("&data=" + URLEncoder.encode(data,"UTF-8"));
//		url.append("&data=" + data);
		url.append("&appkey=" + "1rqW1r97");
		url.append("&secretKey=" +"28lh22NGZ97s5w57");
		String result = HttpUtils.post(url.toString());
		System.out.println(url.toString());
		System.out.println(result);
	}
	
	
	
	public static String getWeixinUrl() {

		StringBuffer buffer = new StringBuffer();
		String weixinUrl = "http://api.mch.tenpay.com/cgi-bin/mch_custom_declare.cgi";
		buffer.append(weixinUrl);

		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("sign_type", "MD5");
		paramMap.put("service_version", "1.0");
		paramMap.put("input_charset", "UTF-8");
		paramMap.put("partner", "1368915602");
		paramMap.put("out_trade_no", "KLL20170424056182021002804");
		// 1广州 8上海 11 广州电子口岸（总署版）
		paramMap.put("customs", "3");
		// 1 新增 2修改（暂只支持郑州综保区，郑州保税物流中心,广州，杭州，宁波） 3 重新推送海关
		paramMap.put("action_type", "1");

		/**
		 * 欧文 补充所有非必要字段参数
		 * 
		 * @author 欧文
		 * @date 2016-9-13
		 */
		paramMap.put("mch_customs_no", "3302462230"); // 如果有海关
																				// 设定,必须增加海关备案号
		paramMap.put("business_type", "1");

		String[] keyArray = paramMap.keySet().toArray(new String[0]);
		Arrays.sort(keyArray);

		// 鎷兼帴鏈夊簭鐨勫弬鏁板悕-鍊间覆
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < keyArray.length; i++) {
			if (i == (keyArray.length - 1)) {
				stringBuilder.append(keyArray[i]).append("=").append(paramMap.get(keyArray[i]));
			} else {
				stringBuilder.append(keyArray[i]).append("=").append(paramMap.get(keyArray[i])).append("&");
			}
		}
		String paramUrl = stringBuilder.toString();
		stringBuilder.append("&key=").append("gUlYPij7ORPBauwNSG7PnbURCI64TjZ6");

		String sign = AlipayMd5Encrypt.md5(stringBuilder.toString()).toUpperCase();
		buffer.append("?").append(paramUrl);
		buffer.append("&sign=").append(sign);

		return buffer.toString();
	}
	
	public static String stringToAscii(String value)  
	{  
	    StringBuffer sbu = new StringBuffer();  
	    char[] chars = value.toCharArray();   
	    for (int i = 0; i < chars.length; i++) {  
	        if(i != chars.length - 1)  
	        {  
	            sbu.append((int)chars[i]).append(",");  
	        }  
	        else {  
	            sbu.append((int)chars[i]);  
	        }  
	    }  
	    return sbu.toString();  
	}  

	private Document document;

	   public void init() throws ParserConfigurationException {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			this.document = builder.newDocument();
	   }

	public void createXml(String fileName) throws Exception {
		Element root = this.document.createElement("scores"); 
		this.document.appendChild(root); 
		Element employee = this.document.createElement("employee"); 
		Element name = this.document.createElement("name"); 
		name.appendChild(this.document.createTextNode("wangchenyang")); 
		employee.appendChild(name); 
		Element sex = this.document.createElement("sex"); 
		sex.appendChild(this.document.createTextNode("m")); 
		employee.appendChild(sex); 
		Element age = this.document.createElement("age"); 
		age.appendChild(this.document.createTextNode("26")); 
		employee.appendChild(age); 
		root.appendChild(employee); 
		TransformerFactory tf = TransformerFactory.newInstance();
			Transformer transformer = tf.newTransformer();
			DOMSource source = new DOMSource(document);
			System.out.println(document);
			System.out.println(source.toString()+"--");
			transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
			StreamResult result = new StreamResult(pw);
			transformer.transform(source, result);
			System.out.println("生成XML文件成功!");
		}

}
